package com.iot08.api.interceptor;

import com.iot08.api.constant.Constant;
import com.iot08.api.service.DeviceDataFlowService;
import com.iot08.api.service.DeviceService;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceDataFlow;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @version 1.0
 * @Description: 检查设备电量和流量拦截器
 * @author: Rock
 * @time: 2021/1/9 16:35
 */
@Slf4j
public class CheckImeiInterceptor extends BaseInterceptor {

    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceDataFlowService deviceDataFlowService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String imei = request.getParameter("imei");
        if (StringUtil.isBlank(imei)) {
            Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            imei = (String) pathVariables.get("imei");
        }
        String path = request.getRequestURI();
        //get请求不做校验
        if (StringUtil.isNotBlank(imei)) {
            if ((!Constant.GET.equals(request.getMethod()) && !path.contains(Constant.VIDEO))
                    || (Constant.GET.contains(request.getMethod()) && path.contains(Constant.VIDEO))) {
                //检查预留省电模式
                Device device = deviceService.findById(imei);
                if (device != null && Const.INT_1.equals(device.getPowerModel())) {
                    log.info("设备电量低拦截，imei={}", imei);
                    returnJson(response, ResponseMap.fail(ResponseEnum.STATUS5003.getCode(), ResponseEnum.STATUS5003.getMsg()));
                    return false;
                }
                if (!path.contains(Constant.DATA_FLOW) || !path.contains(Constant.HEALTH_FUNCTION)) {
                    //检查设备流量限额断网
                    DeviceDataFlow deviceDataFlow = deviceDataFlowService.findById(imei);
                    if (deviceDataFlow != null && Const.INT_1.equals(deviceDataFlow.getStatus())) {
                        log.info("设备网络已断开（已达设定流量套餐），不能使用微聊定位等功能，imei={}", imei);
                        returnJson(response, ResponseMap.fail(ResponseEnum.STATUS5005.getCode(), ResponseEnum.STATUS5005.getMsg()));
                        return false;
                    }
                }
            }
        }
        return true;
    }

}
